/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.pitkley.jocabulary;

import java.io.*;
import java.util.*;
import java.io.BufferedWriter;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author pit
 */
public class Unit {

    private static final String baseURL = "http://jocabulary.pitkley.de/data/";
    private static final File workingDirectory = new File(Util.getWorkingDirectory("jocabulary"), "data/");
    private FileDownloader fd = new FileDownloader(baseURL, workingDirectory);
    private ArrayList<Vocable> vocab = new ArrayList<Vocable>();
    private int askedVocab = 0;
    private String unitName;
    private String cleanName;
    private int onlineRevision;
    private int localRevision;

    Unit(String pUnitName, String pCleanName, int pOnlineRevision) throws IOException {
        unitName = pUnitName;
        cleanName = pCleanName;
        onlineRevision = pOnlineRevision;

        fd.fileExists(unitName + ".json");
    }

    @Override
    public String toString() {
        return this.cleanName;
    }

    public void loadVocab() {
        if (fileExists()) {
            parseFile();
            if (updateAvailable()) {
                fd.downloadFile(unitName + ".json");
                parseFile();
            }
        } else {
            fd.downloadFile(unitName + ".json");
            parseFile();
        }
    }

    public String getUnitName() {
        return unitName;
    }

    public String getCleanName() {
        return cleanName;
    }

    public int getAskedCount() {
        return askedVocab;
    }

    public Vocable getVocable(int index) {
        return (Vocable) vocab.get(index);
    }

    public void resetStats() {
        for (Vocable v : vocab) {
            v.setTimesCorrect(0);
        }
    }

    private boolean fileExists() {
        File f = new File(workingDirectory.getAbsolutePath() + "/" + unitName + ".json");
        return f.exists();
    }

    private boolean updateAvailable() {
        return (onlineRevision > localRevision);
    }

    private void parseFile() {
        vocab.clear();
        try {
            String jsonString = new BufferedReader(new InputStreamReader(new FileInputStream((workingDirectory.getAbsolutePath() + "/" + unitName + ".json")), "UTF8")).readLine();
            JSONObject json = new JSONObject(jsonString);
            localRevision = json.getInt("Revision");
            JSONArray jVocab = json.getJSONArray("Vocab");
            for (int i = 0; i < jVocab.length(); i++) {
                JSONObject jo = jVocab.getJSONObject(i);
                Vocable v = new Vocable(this);

                JSONArray jNativeWords = jo.getJSONArray("NativeWords");
                String[] tempNativeWords = new String[jNativeWords.length()];
                for (int j = 0; j < jNativeWords.length(); j++) {
                    tempNativeWords[j] = jNativeWords.getString(j);
                }
                v.setNativeWords(tempNativeWords);

                JSONArray jTranslations = jo.getJSONArray("Translations");
                String[] tempTranslations = new String[jTranslations.length()];
                for (int j = 0; j < jTranslations.length(); j++) {
                    tempTranslations[j] = jTranslations.getString(j);
                }
                v.setTranslations(tempTranslations);

                v.setTimesCorrect(jo.getInt("TimesCorrect"));

                vocab.add(v);
            }
        } catch (Exception ex) {
        }
    }

    public void writeFile() {
        try {
            JSONObject jRoot = new JSONObject();
            jRoot.put("Revision", localRevision);

            JSONArray jVocab = new JSONArray();
            Iterator it = vocab.iterator();
            while (it.hasNext()) {
                Vocable v = (Vocable) it.next();
                JSONObject jVocable = new JSONObject();
                JSONObject jVocabInfo = new JSONObject();

                JSONArray nativeWords = new JSONArray();
                for (String s : v.getNativeWords()) {
                    nativeWords.put(s);
                }

                JSONArray translations = new JSONArray();
                for (String s : v.getTranslations()) {
                    translations.put(s);
                }

                jVocabInfo.put("NativeWords", nativeWords);
                jVocabInfo.put("Translations", translations);
                jVocabInfo.put("TimesCorrect", v.getTimesCorrect());

                jVocab.put(jVocabInfo);
            }

            jRoot.put("Vocab", jVocab);
            String json = jRoot.toString();
            BufferedWriter file = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(workingDirectory.getAbsolutePath() + "/" + unitName + ".json"), "UTF8"));
            file.write(json);
            file.flush();
            file.close();
        } catch (Exception e) {
        }
    }

    public List<Vocable> getVocab() {
        return vocab;
    }
}
